package com.server.system.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.server.model.all.system.bo.AddSmsLogOperationBo;
import com.server.model.all.system.bo.JudgementSmsBo;
import com.server.model.all.enums.sms.SendSmsStatusEnum;
import com.server.model.all.enums.YesNoEnum;
import com.server.common.code.error.BusinessException;
import com.server.common.code.utils.BeanUtils;
import com.server.model.all.system.entity.SmsOperationLogEntity;
import com.server.system.mapper.SmsOperationLogMapper;
import com.server.system.service.SmsOperationLogService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class SmsOperationLogServiceImpl extends ServiceImpl<SmsOperationLogMapper, SmsOperationLogEntity> implements SmsOperationLogService {

    @Resource
    private SmsOperationLogMapper smsOperationLogMapper;

    @Override
    public int addSmsLogOperation(AddSmsLogOperationBo addSmsLogOperationBo) {
        SmsOperationLogEntity smsOperationLogEntity = BeanUtils.copyProperties(addSmsLogOperationBo,SmsOperationLogEntity.class);
        return smsOperationLogMapper.insert(smsOperationLogEntity);
    }

    @Override
    public boolean judgementSms(JudgementSmsBo judgementSmsBo) {
        LambdaQueryWrapper<SmsOperationLogEntity> lambdaQueryWrapper =
                new LambdaQueryWrapper<SmsOperationLogEntity>()
                .eq(SmsOperationLogEntity::getMobile, judgementSmsBo.getMobile())//手机号
                .eq(SmsOperationLogEntity::getStatus, SendSmsStatusEnum.SEND.getCode())//已发送
                .eq(SmsOperationLogEntity::getSmsType, judgementSmsBo.getSmsType())//短信类型
                .lt(SmsOperationLogEntity::getCreateTime, DateUtil.offsetMinute(new Date(), 30))//小于等于30分钟内
                .orderByDesc(SmsOperationLogEntity::getSmsOperationLogId);//倒序

        //获取最后一条手机号的短信验证码
        List<SmsOperationLogEntity> smsOperationLogEntityList = smsOperationLogMapper.selectList(lambdaQueryWrapper);

        //找不到短信验证码
        if(ObjectUtils.isEmpty(smsOperationLogEntityList)){
            throw new BusinessException("短信验证码已失效,请重新获取");
        }
        SmsOperationLogEntity smsOperationLogEntity = smsOperationLogEntityList.get(0);
        //状态改为已验证
        smsOperationLogEntity.setStatus(SendSmsStatusEnum.VERIFY.getCode());

        int update = smsOperationLogMapper.updateById(smsOperationLogEntity);
        return update == YesNoEnum.YES.getCode();
    }
}
